﻿#define _CRT_SECURE_NO_WARNINGS 1

// C++中的构造函数和析构函数详解
// 类的默认成员函数
// 空类的概念
//A1不是，A2是
class A1
{
public:
	void f1() {}
};

class A2 {};

int main()
{
	return 0;
}

//构造函数的概念
//麻烦的学生类~
#include<iostream>
using namespace std;

class Student
{
public:
	void Init(const char* name,int age, const char* ID)
	{
		strcpy(_name, name);
		_age = age;
		strcpy(_ID, ID);
	}
	void Print()
	{
		cout <<"学生姓名：" << _name << endl;
		cout <<"学生年龄：" << _age << endl;
		cout <<"学生学号：" << _ID << endl;
	}
private:
	char _name[20];
	int _age;
	char _ID[20];
};

int main()
{
	Student stu1;
	stu1.Init("zhangsan", 21, "20001216A11");
	
	stu1.Print();
	return 0;
}

//使用构造函数的学生类
class student
{
public:
	//无参构造函数
	student()
	{
		strcpy(_name, "xxxxxx");
		_age = 0;
		strcpy(_id, "xxxxxxx");
	}
	//有参构造函数
	student(const char*name,int age,const char* id)
	{
		strcpy(_name, name);
		_age = age;
		strcpy(_id, id);
	}
	void print()
	{
		cout << "学生姓名：" << _name << endl;
		cout << "学生年龄：" << _age << endl;
		cout << "学生学号：" << _id << endl;
	}
private:
	char _name[20];
	int _age;
	char _id[20];
};

int main()
{
	student stu1;//调用了无参的构造函数
	stu1.print();

	student stu2("zhangsan", 21, "20001216a11");//调用有参的构造函数
	stu2.print();
	return 0;
}

//构造函数的语法特性
//随机值的初始化 
class P
{
public:
	P()
	{
		cout << "P()" << endl;
		_P = 0;
	}
private:
	int _P;
};

class Student
{
public:
	void Print()
	{
		cout << "学生姓名：" << _name << endl;
		cout << "学生年龄：" << _age << endl;
		cout << "学生学号：" << _ID << endl;
	}
private:
	char _name[20];
	int _age;
	char _ID[20];

	P p1; //对自定义类型调用对应的默认构造函数
};

int main()
{
	Student stu1;//调用默认的构造函数
	stu1.Print();

	return 0;
}

//内置类型成员变量在类中声明时可以给默认值。 

class Student
{
public:
	void Print()
	{
		cout << "学生姓名：" << _name << endl;
		cout << "学生年龄：" << _age << endl;
		cout << "学生学号：" << _ID << endl;
	}
private:
	char _name[20] = "xxxx"; //注意这里还是声明,声明给缺省值
	int _age = 0;
	char _ID[20] = "xxxxxxxx";
};

int main()
{
	Student stu1;//调用默认构造函数
	stu1.Print();

	return 0;
}

//析构函数
class Student
{
public:
	void Print()
	{
		cout << "学生姓名：" << _name << endl;
		cout << "学生年龄：" << _age << endl;
		cout << "学生学号：" << _ID << endl;
	}
	~Student()//析构函数
	{
		cout << "~Student()" << endl;
	}
private:
	char _name[20];
	int _age;
	char _ID[20];
};

int main()
{
	Student stu1;//调用默认构造函数
	stu1.Print();

	return 0;
}